package com.xiaoxin.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.xiaoxin.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author xiaoxiaode
 * @date 2021-09-10-10:27
 **/
@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    public boolean likeOrDislike(Long userId, Long likeUserId, boolean isLike) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
            List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
            // 未喜欢则添加
            if (CollUtil.isEmpty(userLikes)) {
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setIsLike(true);
                userLike.setUpdated(System.currentTimeMillis());
                userLike.setCreated(System.currentTimeMillis());
                mongoTemplate.save(userLike);
            } else {
                // 已喜欢则修改
                Update update = Update.update("isLike", isLike).set("updated", System.currentTimeMillis());
                mongoTemplate.updateFirst(query, update, UserLike.class);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public  List<UserLike> likeCounts(Long userId) {
        Query query=Query.query(Criteria.where("userId").is(userId));
        List<UserLike> likesCounts = mongoTemplate.find(query, UserLike.class);
        return likesCounts;
    }

    @Override
    public List<UserLike> likeToo(Long userId, List<Long> likeUserIds) {
        Query query=Query.query(Criteria.where("userId").in(likeUserIds).and("likeUserId").is(userId));
        List<UserLike> likeToo = mongoTemplate.find(query, UserLike.class);
        return likeToo;
    }

    @Override
    public List<UserLike> likeMe(Long userId) {
        Query query=Query.query(Criteria.where("likeUserId").is(userId));
        List<UserLike> likeMe = mongoTemplate.find(query, UserLike.class);
        return likeMe;
    }

    @Override
    public Boolean booleanLike(Long userId, Long likeUserId) {
        Query query=Query.query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId));
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        return userLike.getIsLike();
    }



}
